package com.rc.web.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.rc.pojo.po.Memory;
import com.rc.pojo.vo.memory.MemoryListVO;
import com.rc.pojo.vo.memory.MemoryVO;
import com.rc.web.converter.MemoryConverter;
import com.rc.web.mapper.MemoryMapper;
import com.rc.web.service.MemoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 记忆服务实现类
 * 提供用户记忆相关的业务逻辑实现
 */
@Service
@RequiredArgsConstructor
public class MemoryServiceImpl extends ServiceImpl<MemoryMapper, Memory> implements MemoryService {
    // 记忆转换器
    private final MemoryConverter memoryConverter;

    /**
     * 获取记忆列表
     * @return 按月份分组的记忆列表VO
     */
    @Override
    public List<MemoryListVO> getList() {
        // 获取当前登录用户的记忆列表
        List<Memory> memoryList = mapper.selectByConId(StpUtil.getLoginIdAsLong());

        // 如果记忆列表为空，返回默认欢迎信息
        if (CollectionUtils.isEmpty(memoryList)) {
            LocalDateTime createTime = LocalDateTime.now();
            MemoryVO memoryVO = MemoryVO.builder()
                    .address("")
                    .createTime(createTime)
                    .img("https://img.tukuppt.com/png_preview/00/49/30/CNQEgKhT9I.jpg!/fw/780")
                    .tag("欢迎加入田园课堂")
                    .build();
            return List.of(MemoryListVO.builder()
                    .time(YearMonth.of(createTime.getYear(), createTime.getMonthValue()))
                    .memory(memoryVO)
                    .build());
        } else {
            // 将记忆按月份分组
            Map<YearMonth, List<MemoryVO>> map = memoryList.stream()
                    .sorted(Comparator.comparing(Memory::getCreateTime))
                    .map(memoryConverter::toVO)
                    .collect(Collectors.groupingBy(item -> YearMonth.from(item.getCreateTime())));

            // 转换为按月份分组的记忆列表VO
            return map.keySet()
                    .stream()
                    .map(key -> MemoryListVO.builder()
                            .time(key)
                            .memory(map.get(key).get(0))
                            .build())
                    .toList();
        }
    }
}
